package com.gcb.xml;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 该类为用DocumentHelper解析一个xml格式的字符串
 * 
 * @author Cre.Gu
 * 
 */
public class DOMParserString {

	private List<Book> list;

	public static void main(String[] args) {
		String sXml = "<books><book id='01'><name>java编程思想</name><price>$17.5</price>"
				+ "</book><book id='02'><name>java核心技术</name><price>$8.5</price>"
				+ "</book></books>";
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(sXml);
		} catch (DocumentException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		DOMParserString dps = new DOMParserString();
		dps.parserBook(doc);
		for (Book book : dps.list) {
			System.out.println(book);
		}
	}

	@SuppressWarnings("unchecked")
	public void parserBook(Document doc) {
		list = new ArrayList<Book>();
		Element root = doc.getRootElement();
		List<Element> book = root.elements("book");
		for (int i = 0; i < book.size(); i++) {
			Element item = book.get(i);
			Book bk = new Book();
			bk.setId(item.attributeValue("id"));
			Element name = item.element("name");
			bk.setName(name.getText());
			Element price = item.element("price");
			bk.setPrice(price.getText());
			list.add(bk);
		}
	}
}